const express = require("express")
const router = express.Router()
const Attendance = require("../models/attendance")
const { log } = require("console")

router.post("/", async (req, res) => {
    try {
        const attendanceData = req.body
        const attendance = await Attendance.addAttendance(attendanceData)
        log("attendance", attendance)
        if (attendance > 0) {
            res.status(200).json({ code: 200, message: "考勤记录添加成功" })
        } else {
            res.status(200).json({ code: 200, message: "考勤记录添加失败" })
        }

    } catch (error) {
        res.status(500).json({ code: 500, message: error.message })
    }
})

router.get("/", async (req, res) => {
    try {
        const { currentPage, pageSize, searchMsg } = req.query
        const attendance = await Attendance.getAllAttendance(currentPage, pageSize, searchMsg)

        res.status(200).json(attendance)
    } catch (err) {
        res.status(500).json({ message: err.message })
    }
})

//更新考勤记录
router.put("/", async (req, res) => {
    const attendanceData = req.body
    try {
        const attendance = await Attendance.updateAttendance(attendanceData)
        if (Number(attendance) > 0) {
            res.status(200).json({ code: 200, message: "考勤记录更新成功" })
        } else {
            res.status(200).json({ code: 200, message: "考勤记录未找到" })
        }
    } catch (error) {
        res.status(500).json({ code: 500, message: error.message })
    }
})

//删除考勤记录
router.delete("/:id", async (req, res) => {
    try {
        const { id } = req.params
        const attendance = await Attendance.deleteAttendance(id)
        if (Number(attendance) > 0) {
            res.status(200).json({ code: 200, message: "考勤记录删除成功" })
        } else {
            res.status(200).json({ code: 200, message: "考勤记录未找到" })
        }


    } catch (err) {
        res.status(500).json({ code: 500, message: err.message })
    }
})

module.exports = router